package net.shao.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;

import net.shao.R;
import net.shao.model.Msg;

import java.util.List;

/**
 * Created by shao on 2016/6/29.
 */
public class TestMsgAdapter extends ArrayAdapter<Msg> {

    private List<Msg> list;

    private int resource;

    private LayoutInflater inflater;

    public TestMsgAdapter(Context context, int resource, List<Msg> objects) {
        super(context, resource, objects);
        this.list = objects;
        this.resource = resource;
        inflater = LayoutInflater.from(context);
    }


    @Override
    public int getCount() {
        if (!list.isEmpty()) {
            return list.size();
        }

        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder = new ViewHolder();
        if (convertView == null) {
            convertView = inflater.inflate(resource, null);
            viewHolder.left_layout = (LinearLayout) convertView.findViewById(R.id.left_layout);
            viewHolder.right_layout = (LinearLayout) convertView.findViewById(R.id.right_layout);
            viewHolder.left_msg = (TextView) convertView.findViewById(R.id.left_msg);
            viewHolder.right_msg = (TextView) convertView.findViewById(R.id.right_msg);
            convertView.setTag(viewHolder);
        }else{
            viewHolder = (ViewHolder) convertView.getTag();
        }

        if (list.get(position).getType() == Msg.TYPE_RECEIVED){
            viewHolder.left_layout.setVisibility(View.VISIBLE);
            viewHolder.right_layout.setVisibility(View.GONE);
            viewHolder.left_msg.setText(list.get(position).getContent());
        }else if(list.get(position).getType() == Msg.TYPE_SENT){
            viewHolder.left_layout.setVisibility(View.GONE);
            viewHolder.right_layout.setVisibility(View.VISIBLE);
            viewHolder.right_msg.setText(list.get(position).getContent());
        }

        return convertView;
    }

    class ViewHolder {
        LinearLayout left_layout;
        LinearLayout right_layout;
        TextView left_msg;
        TextView right_msg;
    }

}
